<?php
class Admin extends Controller
{
	public function _default()
	{
		$group = isset($_GET['group']) && $_GET['group'] ? trim($_GET['group']) : '';
		$where = $group ? "group='$group'" : '';
		$userList = AdminModel::getList($where);
		$this->assign('userList', $userList);
		$this->assign('groups', AdminModel::$groups);
		$this->display('admin.tpl');
	}
	
	public function add()
	{
		if (isset($_POST['act'])){
			$act = trim($_POST['act']);
			
			$alias = isset($_REQUEST['alias']) ? trim($_REQUEST['alias']) : '';
			$group = isset($_POST['group']) ? trim($_POST['group']) : 'admin';
			$permission = isset($_POST['permission']) ? $_POST['permission'] : '';
			if ($act=='add'){
				$uname = isset($_REQUEST['uname']) && $_REQUEST['uname'] ? trim($_REQUEST['uname']) : Util::msgRedirect('缺少用户名');
				$passwd = isset($_POST['passwd']) && $_POST['passwd'] ? trim($_POST['passwd']) : Util::msgRedirect('缺少密码');
				$passwd2 = isset($_POST['passwd2']) && trim($_POST['passwd'])==$_POST['passwd2'] ? '' : Util::msgRedirect('两次输入的密码不一致');
				$userInfo = AdminModel::get('', $uname);
				if ($userInfo){
					Util::msgRedirect('用户名重复');
				}
				
				$passwd = md5($passwd);
				if (AdminModel::add($uname, $passwd, $alias, $group, $permission)){
					Util::msgRedirect('添加成功', $GLOBALS['short_router']);
				}else{
					Util::msgRedirect('操作失败');
				}
			}elseif ($act=='edit'){
				$uid = isset($_POST['uid']) ? trim($_POST['uid']) : Util::msgRedirect('缺少UID');
				$passwd = isset($_POST['passwd']) && $_POST['passwd'] ? trim($_POST['passwd'])==trim($_POST['passwd2']) ?
							 md5(trim($_POST['passwd'])) : Util::msgRedirect('两次输入密码不一致') : '';
				$data = array(
					'alias'		=> $alias,
					'group'		=> $group,
					'permission'=> $permission,
				);
				if ($passwd){
					$data['passwd'] = $passwd;
				}
				if (AdminModel::update($uid, $data)){
					Util::msgRedirect('修改成功', $GLOBALS['short_router']);
				}else{
					Util::msgRedirect('修改失败');
				}
			}
			
		}else{
			$this->assign('groups', AdminModel::$groups);
			$this->display('admin_add.tpl');
		}
	}
	
	public function edit()
	{
		$uid = isset($_REQUEST['uid']) && trim($_REQUEST['uid']) ? intval($_REQUEST['uid']) : Util::msgRedirect('缺少UID');
		$userInfo = AdminModel::get($uid);
		if (!$userInfo) {
			Util::msgRedirect('用户不存在');
		}
		$this->assign('act', 'edit');
		$this->assign('arr', $userInfo);
		$this->add();
	}
}